<template>
  <ThreeBox ref="container"></ThreeBox>
</template>

<script setup>
import ThreeBox from "../../components/ThreeBox.vue";
import { ref, onMounted } from "vue";
import * as THREE from "../../third/three/three.module.js";
import {
  CSS3DRenderer,
  CSS3DObject,
} from "../../third/three/jsm/renderers/CSS3DRenderer.js";
import "leaflet/dist/leaflet.css";
import L from "leaflet";

const container = ref(null);
let threeBox = null;
let threePara = null;
let scene = new THREE.Scene();
let mouseX = 0;
let mouseY = 0;

function createMap() {
  L.map("map", {
    crs: L.CRS.EPSG4326,
    layers: [
      L.tileLayer(
        "https://t{s}.tianditu.gov.cn/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=23c64b6db1d90eaeb7516746514ef956",
        {
          maxZoom: 17,
          tileSize: 256,
          zoomOffset: 1,
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
        }
      ),
    ],
    zoomControl: false,
    attributionControl: false,
  }).setView([43.800086975097656, 125.24789571762085], 15);
}

function animate() {
  requestAnimationFrame(animate);
  render();
}

function render() {
  threePara.camera.position.x += (-mouseX - threePara.camera.position.x) * 1;
  threePara.camera.position.y += (mouseY - threePara.camera.position.y) * 1;
  threePara.camera.lookAt(0, 0, 0);
  threePara.renderer.render(scene, threePara.camera);
}

function init() {
  //创建地图容器
  let element = document.createElement("div");
  element.id = "map";
  element.style.width = "1920px";
  element.style.height = "1080px";
  element.style.boxShadow = "0px 0px 200px rgba(255, 255, 255, 0.5)";

  let css3Obj = new CSS3DObject(element);
  css3Obj.position.set(0, 0, 0);
  scene.add(css3Obj);

  //相机
  threePara.camera = new THREE.PerspectiveCamera(
    45,
    threeBox.clientWidth / threeBox.clientHeight,
    1,
    10000
  );
  threePara.camera.position.set(0, 2000, 2000);
  threePara.camera.lookAt(0, 0, 0);

  //渲染器
  threePara.renderer = new CSS3DRenderer();
  threePara.renderer.setSize(threeBox.clientWidth, threeBox.clientHeight);
  threeBox.appendChild(threePara.renderer.domElement);

  threeBox.addEventListener("mousemove", function (event) {
    mouseX = event.layerX - threeBox.clientWidth / 2;
    mouseY = event.layerY - threeBox.clientHeight / 2;
  });
}

onMounted(() => {
  threeBox = container.value.threeBox;
  threeBox.style.backgroundColor = "black";
  threePara = container.value.threePara;
  init();
  animate();
  createMap();
});
</script>
